from __future__ import division
import sys,os
from time import sleep
from src.Equipments.LockIn import SR830
from src.Equipments.RFGenerator import E8257D,N5181A
from src.Data.DataStructure import Data
from src.Equipments.multimeter import AgilentMulti
from src.Equipments.EDMR_magnet import EDMRmagnet

from numpy import *
#import pylab as plb
User="Christophe"
home_path=os.getcwd()+os.sep#Current path to this program
sys.path.append(home_path+"src"+os.sep)
#data_path=home_path+"data"+os.sep#For saving later on data
data_path=home_path+"Users"+os.sep+User+os.sep+"data"#+os.sep
#RF=E8257D("GPIB0::10::INSTR","FM")
RF=N5181A("GPIB0::14::INSTR","FM")
lockin=SR830("GPIB0::9::INSTR")



### Parameters - RF setup
#########################################################

def setRFmod(modon,LFouton):#Modulation On = True, LFOutput On = True
    RF.modulation = "AM"
    
    if modon == True:
        RF.Set_Modulation(5012,100) #Frequency Hz, Modulation deviation kHz / amplitude dB
        RF.Set_Modulation_Output(modon,LFouton)
    
def setlockin(modfreq,timeconst,harm=2,mod=1):
    lockin.Reset_Memory()
    lockin.Set_Time_Constant(timeconst)
    lockin.Set_Harm(harm)
    lockin.Set_InterExter_Mode(mod)
    lockin.Set_Freq(modfreq)
    sleep(1)

def fieldsweep(Bmin,Bmax,resB,modfreq,timeconst):
    
    
    
    magnet=EDMRmagnet(False)
    magnet.OpenRessource()
    magnet.SetMagneticField(Bmin, "gauss")
    sleep(1)
    
    number_of_points = int((Bmax-Bmin)/resB)
    B = Bmin
    
    data=Data(given_name="test1",
        path=data_path,
        comments="#36 Vpp = 4.13 Bi = 60G, Bf = 95G, res = 0.2G, bias = 3V, light = 7V",
        rows=number_of_points,
        columns=3,#Field, 2 phases
        light=True,
        temperature=5,#K
        scan_mode="field",
        phase=0,#in degree
        modulation_frequency=modfreq,#in kHz
        modulation_amplitude=2,#in V,
        time_constant=0.3, #in s
        frequency=200,#MHz
        power=0,#dB
        picture_saving_format='eps',
        user=User)
    
    for i in range(0,number_of_points):
        data.data[i,0] = B

        #read points
        sleep(3*timeconst)
        xy = lockin.Read_XY()
        data.data[i,1]=xy[0]
        data.data[i,2]=xy[1]
        print data.data[i]
        
        B=B+resB
        magnet.SetMagneticField(B, "gauss")

    magnet.CloseRessource()

    data.Save_data()

def freqsweep(B,fmin,fmax,fres):

    number_of_points = (fmax-fmin)/fres
    RF.Set_Frequency(fmin)
    
    

if __name__ == "__main__":
    modfreq=32520 #Hz
    timeconst = 0.3 #s
    Bmin = 60 #G
    Bmax = 95 #G
    resB = 0.2 #G
    setlockin(modfreq,timeconst) #Hz,V
    fieldsweep(Bmin,Bmax,resB,modfreq,timeconst) #MHz,G
  
